package com.whj.apipassenger.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.whj.apipassenger.service.TokenService;
import com.whj.internalcommon.constant.CommonStatusEnum;
import com.whj.internalcommon.constant.IdentityConstant;
import com.whj.internalcommon.constant.TokenTypeConstants;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.dto.TokenResult;
import com.whj.internalcommon.response.TokenResponse;
import com.whj.internalcommon.utils.JwtUtils;
import com.whj.internalcommon.utils.RedisTokenKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/2 - 01 - 02 - 16:14 
 * @Description: com.whj.apipassenger.service.impl
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult refreshToken(String refreshTokenSrc) {

        //解析refreshToken
        TokenResult tokenResult = JwtUtils.checkToken(refreshTokenSrc);
        if (tokenResult == null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        //读取redis中的token
        String identity = tokenResult.getIdentity();
        String phone = tokenResult.getPhone();

        //生成refreshTokenKey
        String refreshTokenKey = RedisTokenKeyUtils.keyByTokenMsg(phone, identity, TokenTypeConstants.REFRESH_TOKEN_TYPE);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);

        //校验refreshToken
        if ((StringUtils.isBlank(refreshTokenRedis)) || (!refreshTokenSrc.trim().equals(refreshTokenRedis))) {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        //生成双token
        String refreshToken = JwtUtils.generatorToken(phone, identity, TokenTypeConstants.REFRESH_TOKEN_TYPE);
        String accessToken = JwtUtils.generatorToken(phone, identity, TokenTypeConstants.ACCESS_TOKEN_TYPE);

        //生成accessTokenRedis
        String accessTokenRedis = RedisTokenKeyUtils.keyByTokenMsg(phone, identity, TokenTypeConstants.ACCESS_TOKEN_TYPE);

        //存入redis
        stringRedisTemplate.opsForValue().set(accessTokenRedis,accessToken,30,TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken,31, TimeUnit.DAYS);

        //响应
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);

        return ResponseResult.success(tokenResponse);
    }
}
